package com.example.jf.jfapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.jf.jfapp.bean.LoginResponse;
import com.example.jf.jfapp.activity.base.BaseActivity;
import com.example.jf.jfapp.bean.response.ErrorResponse;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.OkHttpUtils;
import com.example.jf.jfapp.utils.RequestUtils;
import com.example.jf.jfapp.widget.GlideCircleTransform;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    private static final int REQUEST_SIGNUP = 0;

    @BindView(R.id.jf_logo)
    ImageView jfLogo;

    @BindView(R.id.input_username)
    EditText inputUsername;

    @BindView(R.id.input_password)
    EditText inputPassword;

    @BindView(R.id.btn_login)
    AppCompatButton btnLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        jfLogo= (ImageView) findViewById(R.id.jf_logo);
        Glide.with(this)
                .load(R.drawable.jf_logo)
                .transform(new GlideCircleTransform(this))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(jfLogo);
    }

    public void login() {
        if (!validate()) {
            onLoginFailed();
            return;
        }
        btnLogin.setEnabled(false);

        showProgressDialog("登陆中...");

        String username = inputUsername.getText().toString();
        String password = inputPassword.getText().toString();

        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();

        HttpUrl.Builder builder = HttpUrl.parse(Constant.URL.USER_LOGIN).newBuilder();

        builder.addQueryParameter("username", username);
        builder.addQueryParameter("password", password);

        Request request = RequestUtils.requestGET(builder.build());

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "登陆失败 ");
                onLoginFailed();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);

                if (response.code() == 200) {
                    LoginResponse loginResponse = new Gson().fromJson(result, LoginResponse.class);
                    //存储用户信息
                    AppConfigUtils.getInstance().saveLoginInfo(LoginActivity.this, loginResponse);
                    AppConfigUtils.getInstance().updateLoginInfo(LoginActivity.this);

                    AppConfigUtils.getInstance().setLoginStatu(LoginActivity.this, false);

                //    App.getInstance().loginIM();
                    //这个是后面用来登陆聊天界面的

//                    App.getContext().login();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            showToast("登陆成功");

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    });

                } else {
                    final ErrorResponse errorResponse = new Gson().fromJson(result, ErrorResponse.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            onLoginFailed();
                            if (errorResponse.getCode() == 211) {
                                Toast.makeText(LoginActivity.this, "用户名不存在", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(LoginActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                            }

                            dismissProgressDialog();
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SIGNUP) {
            if (resultCode == RESULT_OK) {
                this.finish();
            }
        }
    }


    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("不登陆不能使用应用，是否退出？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.show();
    }


    public void onLoginFailed() {
        btnLogin.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

        String username = inputUsername.getText().toString();
        String password = inputPassword.getText().toString();

        if (username.isEmpty()) {
            inputUsername.setError("用户名不能为空");
            valid = false;
        } else {
            inputUsername.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            inputPassword.setError("密码不能为空，并且大于4位小于10位");
            valid = false;
        } else {
            inputPassword.setError(null);
        }

        return valid;
    }


    @OnClick({R.id.jf_logo, R.id.input_username, R.id.input_password, R.id.btn_login, R.id.link_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.link_register:
                Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivityForResult(intent, REQUEST_SIGNUP);
                break;
        }
    }

}
